package com.ncs.nc.entity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.UUID;

@Component
public class RedisPublisher {

    /**
     * 定义日志
     */
    private static final Logger log = LoggerFactory.getLogger(RedisPublisher.class);

    /**
     * 定义日期对象--保证并发访问时的线程安全
     */
    private ThreadLocal<SimpleDateFormat> localDate = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddHHmmss"));

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 消息所在的"频道","主题"
     */
    private ChannelTopic topic = new ChannelTopic(Constant.REDIS_MSG_TOPIC);

    /**
     * 定时发送消息--每隔5秒发送一次
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void timeSendMsg() {
        //随机生成消息ID
        String msgId = UUID.randomUUID().toString().replaceAll("-", "");
        //发送者
        String publisher = "定时任务--debug";
        //消息内容
        String msgContent = "双12秒杀：" + msgId;
        //发送时间
        String sendDate = LocalDate.now().toString();
        //构造消息对象
        RedisMsg rm = new RedisMsg(msgId, publisher, msgContent, sendDate);

        this.publish(rm);
    }

    /**
     * 推送消息
     */
    public void publish(final RedisMsg redisMsg) {
        //发布消息
        redisTemplate.convertAndSend(topic.getTopic(), redisMsg);
        log.info("成功发送消息:{}\n", redisMsg);
    }

}
